package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.behavior.service.ApArticleRelationService;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.behavior.service.ApUnlikesBehaviorService;
import com.heima.common.exception.CustomException;
import com.heima.model.behavior.dtos.ApArticleRelationDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Wrapper;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@Service
public class ApArticleRelationServiceImpl implements ApArticleRelationService {

    @Autowired
    ApLikesBehaviorService apLikesBehaviorService;
    @Autowired
    ApUnlikesBehaviorService apUnlikesBehaviorService;
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Override
    public Map findApArticleRelation(ApArticleRelationDto dto) {
        Map<String, Object> map = new HashMap<>();
        map.put("isLike",false);
        map.put("isunlike",false);
        if (dto == null || dto.getArticleId() == null || dto.getEntryId() == null){
            return map;
        }


        // 查询行为实体
        ApBehaviorEntry behaviorEntry = null;
        if (dto.getType() == 1) {
            behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(dto.getEntryId(), null);
        } else {
            behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(null,dto.getEntryId());
        }

        if (behaviorEntry == null){
            return map;
        }

        // 行为实体id
        map.put("entryId",behaviorEntry.getId());
        // 插叙文章点赞
        ApLikesBehavior apLikesBehavior = apLikesBehaviorService.getOne(Wrappers.<ApLikesBehavior>lambdaQuery()
                .eq(ApLikesBehavior::getArticleId, dto.getArticleId())
                .eq(ApLikesBehavior::getEntryId, behaviorEntry.getId()));

        if (apLikesBehavior != null && apLikesBehavior.getOperation()==0) {
            map.put("islike", true);
        }

        // 查询文章不喜欢
        ApUnlikesBehavior apUnlikesBehavior = apUnlikesBehaviorService.getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery()
                .eq(ApUnlikesBehavior::getEntryId,behaviorEntry.getId())
                .eq(ApUnlikesBehavior::getArticleId,dto.getArticleId())
        );
        if (apUnlikesBehavior != null && apUnlikesBehavior.getType().intValue() == 0) {
            map.put("isunlike", true);
        }

        return map;
    }
}
